package com.fgba.express.core.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fgba.express.comm.enums.RequestForm;
import com.fgba.express.core.controller.handle.ControllerModelMethod;
import com.fgba.express.core.controller.handle.ControllerValidationHandle;
import com.fgba.express.core.dto.BaseDto;
import com.fgba.express.core.entity.BaseEntity;
import com.fgba.express.core.mapstruct.BaseStruct;
import com.fgba.express.core.search.BaseSearch;
import com.fgba.express.core.service.ICrudService;
import com.fgba.express.core.utils.GenericUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author fgba
 */
public abstract class BaseController<T extends BaseEntity, D extends BaseDto, Q extends BaseSearch, S extends ICrudService<T, D, Q>, C extends BaseStruct<T, D, Q>> implements ControllerModelMethod<T, D>, ControllerValidationHandle<T, D> {

    @Autowired
    protected S service;

    @Autowired
    protected C struct;

    @Resource
    protected HttpServletRequest request;

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 域对象类型
     */
    protected Class<T> entityClass;

    public BaseController() {
        this.entityClass = GenericUtil.getSuperGenericClassIndex0(this.getClass());
    }

    /**
     * 加载
     *
     * @param id
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "加载", notes = "根据ID加载")
    @GetMapping("/id/{id}")
    public D edit(@PathVariable Long id) throws Exception {
        T entity = service.getById(id);
        afterEdit(entity);
        D model = struct.dtoConvertEntity(entity);
        afterEdit(model);

        return model;
    }

    /**
     * 分页查询
     *
     * @param search
     * @param page
     * @param size
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/list-page")
    public IPage<D> listPage(Q search,
                             @RequestParam(name = "page", defaultValue = "1", required = false) Integer page,
                             @RequestParam(name = "size", defaultValue = "10", required = false) Integer size) {
        IPage<D> result = service.getListPage(search, page, size);
        return result;
    }

    /**
     * 根据实体条件查询
     *
     * @return
     */
    @ApiOperation(value = "查询", notes = "根据实体条件查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<D> list(Q search) {
        List<D> list = service.getList(search);
        return list;
    }

    /**
     * 新增
     */
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public D save(@RequestBody D dto) throws Exception {

        LocalDateTime now = LocalDateTime.now();
        createValidation(dto);
        //添加前处理model类
        beforeSave(dto);
        T entity = struct.entityConvertDto(dto);
        entity.setCreateTime(now);
        entity.setModifiedTime(now);
        //添加前处理实体类
        beforeSave(entity);
        service.save(entity);
        dto.setId(entity.getId());
        afterSave(dto);

        return dto;
    }

    /**
     * 修改
     *
     * @param dto
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "修改", notes = "修改")
    @PutMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public D update(@RequestBody D dto) throws Exception {
        updateValidation(dto);
        //修改前处理model类
        beforeUpdate(dto);
        T entity = struct.entityConvertDto(dto);
        entity.setModifiedTime(LocalDateTime.now());
        //修改前处理实体类
        beforeUpdate(entity);
        service.updateById(entity);
        dto.setId(entity.getId());
        afterUpdate(dto);

        return dto;
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除", notes = "根据ID删除")
    @DeleteMapping("/delete/{id}")
    @Transactional(rollbackFor = Exception.class)
    public void delete(@PathVariable Long id) throws Exception {
        service.removeById(id);
    }

    /**
     * 批量删除
     */
    @ApiOperation(value = "删除", notes = "批量删除")
    @DeleteMapping("/deleteByIds")
    public void delete(@RequestParam List<Long> ids) {
        service.removeByIds(ids);
    }

    protected Boolean requestFormIsWx() {
        String requestFrom = request.getHeader("request-from");
        return RequestForm.WECHAT.getName().equals(requestFrom);
    }
}
